import _ from 'lodash'

// 对最外层路由的children进行扁平处理
export function routesFlat(routes) {
  const _routes = _.cloneDeep(routes)

  _routes.forEach((item) => {
    if (item.children && item.children.length >= 1) {
      item.children = flat(item.children, item.path)
    }
  })

  return _routes
}
// 扁平处理函数
function flat(routes, parent_path) {
  let arr = []

  routes.forEach((route) => {
    const { children, ...reset } = route
    reset.path = parent_path + '/' + reset.path

    if (children && children.length > 0) {
      // 如果父级存在component，则不需要进行扁平化处理
      if (!reset.component) {
        arr.push(reset)
        arr = arr.concat(...flat(children, reset.path))
      } else {
        reset.children = [].concat(...flat(children, reset.path))
        arr.push(reset)
      }
    } else {
      arr.push(reset)
    }
  })

  return arr
}
